package cn.jtfadmin.base.filesystem.controller;

import cn.jtfadmin.base.filesystem.config.FileSystem;
import cn.jtfadmin.base.lang.common.domain.dto.ResultDTO;
import cn.jtfadmin.base.lang.common.utils.RequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 文件-文件上传
 */
@RestController
public class FileUploadController {

    @Autowired
    private FileSystem fileSystemConfig;


    /**
     * 获取文件类型支持上传的文件后缀名
     *
     * @param type 文件类型
     * @return
     */
    @GetMapping(value = "/file/findUploadTypes")
    public ResultDTO<String> getUploadTypes(@NotBlank @RequestParam String type) {
        List<String> typeSuffix = fileSystemConfig.getTypeSuffix(type);
        return ResultDTO.
                successData(
                        typeSuffix.stream().map(t -> "." + t).collect(Collectors.joining(","))
                );
    }

    /**
     * 文件上传，form表单文件上传,一个type字段标识上传文件类型(联系后管看什么类型)，一个表单上传域
     *
     * @param file 文件
     * @param type 文件类型
     * @param updateFileName 是否更新文件名
     * @return
     */

    @ResponseBody
    @PostMapping(value = "/file/upload",consumes= MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResultDTO<List<String>> upload(@NotNull MultipartFile file, @NotBlank @RequestParam String type,
                                          @RequestParam(required = false, defaultValue = "true") Boolean updateFileName) throws IOException {
        if (!StringUtils.hasText(type) || !fileSystemConfig.validType(type)) {
            throw new IllegalArgumentException("参数type不存在");
        }
        List<String> list = new LinkedList<>();
        list.add(fileSystemConfig.upload(file, type, updateFileName));
        return ResultDTO.successData(list);
    }

}
